package com.cus.tom.transfer.frag;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.cus.tom.transfer.R;
import com.cus.tom.transfer.adapter.AppAdapter;
import com.cus.tom.transfer.databinding.FragAppBinding;
import com.cus.tom.transfer.utils.ComUtility;
import com.cus.tom.transfer.utils.Read;
import com.cus.tom.transfer.utils.Utils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.plata.base.aclr.common.ITask;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AppFragment extends BaseFragment {

    FragAppBinding binding;
    AppAdapter adapter;
    int totalNum;
    long totalSize;
    public static Set<String> set = new HashSet<>();
    final int type, index;

    public AppFragment(int type, int index) {
        this.type = type;
        this.index = index;
    }

    private boolean checkPermission() {
        if (!XXPermissions.isGranted(getActivity(), Permission.MANAGE_EXTERNAL_STORAGE)) {
            binding.noDataTv.setVisibility(View.VISIBLE);
            binding.noDataTv.setText("去授权");
            binding.noDataTv.setTextColor(Color.WHITE);
            binding.noDataTv.setBackgroundResource(R.drawable.btn_bg);
            binding.noDataTv.setOnClickListener(v -> {
                reqPermission();
            });
            return false;
        }
        binding.noDataTv.setText("没有数据");
        binding.noDataTv.setTextColor(Color.LTGRAY);
        binding.noDataTv.setBackground(null);
        binding.noDataTv.setOnClickListener(null);
        return true;
    }

    private void reqPermission() {
        XXPermissions.with(this).permission(Permission.MANAGE_EXTERNAL_STORAGE).request(new OnPermissionCallback() {
            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                if (allGranted) {
                    List<ApplicationInfo> allApps = new Read().loadApps();
                    if (allApps.isEmpty()) {
                        binding.noDataTv.setVisibility(View.VISIBLE);
                    }
                    adapter = new AppAdapter(allApps, AppFragment.this);
                    binding.list.setAdapter(adapter);
                }
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragAppBinding.inflate(inflater, container, false);
        binding.list.setLayoutManager(new GridLayoutManager(getActivity(), 4));

        List<ApplicationInfo> allApps = new Read().loadApps();
        if (allApps.isEmpty()) {
            if (!checkPermission()) {
                binding.noDataTv.setVisibility(View.VISIBLE);
            }
        }
        adapter = new AppAdapter(allApps, this);
        binding.list.setAdapter(adapter);
        binding.top.all.setOnClickListener(v -> {
            boolean bo = !binding.top.all.isSelected();
            binding.top.all.setSelected(bo);
            adapter.selectAll(bo);
            update();
        });
        if (!set.isEmpty()) {
            adapter.setSelect(set);
            update();
        }
        binding.next.setOnClickListener(v -> {
            Intent i = new Intent();
            set.clear();
            set.addAll(adapter.getSelect());
            i.putExtra("num", totalNum);
            i.putExtra("size", totalSize);
            getActivity().setResult(Activity.RESULT_OK, i);
            getActivity().finish();
        });

        if (type == 0) {
            binding.top.back.setOnClickListener(v -> {
                getActivity().finish();
            });
        } else {
            binding.bottom.setVisibility(View.GONE);
            binding.top.getRoot().setBackgroundColor(0xfff3f3f3);
            binding.top.back.setVisibility(View.INVISIBLE);
        }

        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (type == 1) {
            set.clear();
            set.addAll(adapter.getSelect());
        }
    }

    ITask task = null;

    public void update() {
        Set<String> now = adapter.getSelect();
        if (now.size() == adapter.getItemCount() && !now.isEmpty()) {
            binding.top.all.setSelected(true);
        } else {
            binding.top.all.setSelected(false);
        }
        if (task != null) {
            task.cancel();
        }
        LoadingDlg dlg = new LoadingDlg().setMsg("正在计算文件大小");
        dlg.setCancelable(false);
        dlg.show(getChildFragmentManager(), "");
        task = new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                try {
                    long size = 0;
                    Set<String> set = new HashSet<>();
                    set.addAll(now);
                    if (type == 0) {
                        for (String name : set) {
                            String str = ComUtility.android_command("pm path " + name);
                            str = str.substring(str.indexOf("/"));
                            File aa = new File(str);
                            size += aa.length();
                        }
                    }
                    long l = size;
                    h.post(() -> {
                        binding.bar.setVisibility(View.GONE);
                        binding.tip.setVisibility(View.VISIBLE);
                        totalNum = set.size();
                        totalSize = l;
                        if (type == 1) {
                            ((FileFragment) getParentFragment()).updateBtn(totalNum, index);
                        }
                        if (totalNum == 0) {
                            binding.tip.setText(R.string.app_num0);
                        } else {
                            binding.tip.setText(String.format(getString(R.string.app_num), set.size(), Utils.formatSize(l)));
                        }
                    });
                } finally {
                    h.post(() -> {
                        if (dlg != null) {
                            dlg.dismiss();
                        }
                    });
                    task = null;
                }
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        };
        binding.bar.setVisibility(View.VISIBLE);
        binding.tip.setVisibility(View.INVISIBLE);
        TaskEngine.getInstance().submit(task);
    }
}
